﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using OutdoorLib.BaseEntity.Infrastructure;
using System;
using Grishko.Tools;
using Grishko.DataTier.SqlSentence;

namespace Grishko.UI
{
    [ToolboxData("<{0}:FilterPanel   runat=server></{0}:FilterPanel>"),
    DefaultProperty("Text")]
    public class FilterPanel : WebControl, IPostBackDataHandler ,IFilterPanel 
    {
        string qListType = "ListTagName";
        string qID = "ID";

        const string AddImageUrlKey = "AddImageUrlKey";
        const string EditImageUrlKey = "EditImageUrlKey";
        const string DeleteImageUrlKey = "DeleteImageUrlKey";
        

        const string FilterSelectorChangeEventKey = "FilterSelectorChangeEventKey";
        const string AddFilterEventKey = "AddFilterEventKey";
        const string RemoveEventKey = "RemoveEventKey";
        const string EditEventKey = "EditEventKey";


        public FilterPanel()
        {


        }

        private string GetProperty(string Key)        
        {
            object text = ViewState[Key];
            if (null == text)
                return string.Empty;
            else
                return (string)text;
        }

       

        public string AddImageUrl
        {

            get
            {
                return GetProperty(AddImageUrlKey);
        
            }
            set
            {
                
                ViewState[AddImageUrlKey] = value;
                
            }
        }

        public string EditImageUrl
        {

            get
            {
                return GetProperty(EditImageUrlKey );

            }
            set
            {
                ViewState[EditImageUrlKey] = value;
                
            }
        }

        public string DeleteImageUrl
        {

            get
            {
                return GetProperty(DeleteImageUrlKey);

            }
            set
            {
                ViewState[DeleteImageUrlKey] = value;
            }
        }

        protected Filter __Filter = null;
        public  virtual  Filter DataSource
        {
            get
            {
                if (null != __Filter)
                    return __Filter;

                //если указан ид фильтра
                if (!string.IsNullOrEmpty(CurrentId))
                {
                    __Filter = AppEnvironment.FilterSource.Get(CurrentId);
                    return __Filter;
                }


                //если указан тип  фильтров
                if (!string.IsNullOrEmpty(CurrentListType))
                {
                    List<Filter> fSet = AppEnvironment.FilterSource.GetFilters(CurrentListType);

                    if (fSet.Count == 0)
                        return null;

                    __Filter = fSet[0];
                    return __Filter;
                }
                return __Filter;
            }
            
        }

        protected virtual string CurrentListType 
        {
            get { return Page.Request.QueryString[qListType]; }
        }

        protected virtual string CurrentId
        {
            get { return Page.Request.QueryString[qID]; }
        }


        protected ListItem[] GetCmbSource()
        {
            
            List<ListItem> result = new List<ListItem>();                  
            if (null == DataSource)
                return result.ToArray<ListItem>();

            List<Filter> fList = AppEnvironment.FilterSource.GetFilters(DataSource.TagName);
            foreach (Filter j in fList)
            {
                ListItem itm = new ListItem();
                itm.Text = j.Caption;
                itm.Value = j.ID;
                itm.Selected = (CurrentId == j.ID);
                itm.Selected = (j.ID == CurrentId);
                result.Add(itm);
            }

            return result.ToArray<ListItem>();
            
        }


        public override void DataBind()
        {
            string d = "";
        
        }
        

        protected override void Render(HtmlTextWriter writer)
        {
            Unit btnWidtch = new Unit("30px");
            Unit PanelHi = new Unit("25px");            
            
            Page.VerifyRenderingInServerForm(this);

            Panel pnl = new Panel() { Width = new Unit("100%"), CssClass = this.CssClass,   Height = PanelHi };

            Table Tbl = new Table() { Width = new Unit("100%"), HorizontalAlign =HorizontalAlign .Left , CellPadding = 0, CellSpacing = 0 };
            TableRow RW = new TableRow() { VerticalAlign = VerticalAlign.Middle, Height = PanelHi };
            
            TableCell ComboBoxCell = new TableCell() { Width = new Unit("250px") };            
            
            DropDownList cmb = new DropDownList() { Width = new Unit("95%") };
            
            if(!this .DesignMode) 
                cmb.Items.AddRange(GetCmbSource());

            cmb.Attributes.Add("onchange", "__doPostBack('" + this.UniqueID + "','" + FilterSelectorChangeEventKey + "'+this.value);");

            ComboBoxCell.Controls.Add(cmb);


            TableCell BtnEditCell = new TableCell() { Width = btnWidtch, CssClass = "Split_Left" };            
            Image  BtnEditControl = new Image() { ImageUrl = EditImageUrl };
            BtnEditControl.Attributes.Add("onclick", "__doPostBack('" + this.UniqueID + "','" + EditEventKey + "');");
            BtnEditCell.Controls.Add(BtnEditControl);


            TableCell BtnAddCell = new TableCell() { Width = btnWidtch };          
           
            Image BtnAddControl = new Image() { ImageUrl = AddImageUrl };
            BtnAddControl.Attributes.Add("onclick", "__doPostBack('" + this.UniqueID + "','" + AddFilterEventKey + "');");
            BtnAddCell.Controls.Add(BtnAddControl);

            TableCell BtnDeleteCell = new TableCell() { Width = btnWidtch};
            Image BtnDeleteControl = new Image () { ImageUrl = DeleteImageUrl };
            BtnDeleteControl.Attributes.Add("onclick", "__doPostBack('" + this.UniqueID + "','" + RemoveEventKey + "');");
            BtnDeleteCell.Controls.Add(BtnDeleteControl);

            TableCell BtnEmptyCell = new TableCell() {  CssClass = "Split_Left" };
            BtnEmptyCell.Text = " &nbsp";
            TableCell[] arr = { ComboBoxCell ,BtnEditCell ,BtnAddCell ,BtnDeleteCell ,BtnEmptyCell};
            RW.Cells .AddRange  (arr );
            Tbl.Rows .Add (RW);
            pnl.Controls.Add(Tbl);
            pnl.Controls.Add(new HiddenField() { ID = this.UniqueID });
            pnl.RenderControl(writer);
         
        }

        #region IPostBackDataHandler Members


        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {   
            if (postDataKey == this.UniqueID)
            {               
                return true;
            }
            return false;
        }

        public void RaisePostDataChangedEvent()
        {
            
            if (Page.Request.Form["__EVENTARGUMENT"].IndexOf(FilterSelectorChangeEventKey) > -1)
                OnFilterSelectorChange();
            if (Page.Request.Form["__EVENTARGUMENT"] == AddFilterEventKey)
                OnAddFilter();
            if (Page.Request.Form["__EVENTARGUMENT"] == RemoveEventKey)
                OnDelete();
            if (Page.Request.Form["__EVENTARGUMENT"] == EditEventKey)
                OnEditFilter();         
        }

        protected virtual void OnFilterSelectorChange()
        {
            string id = Page.Request.Form["__EVENTARGUMENT"].Replace(FilterSelectorChangeEventKey, string.Empty);
            QueryStringTools.RefreshPage(string.Format("ID={0}", id));
        }

        protected virtual void OnAddFilter()
        {
            string sListType = AppEnvironment.FilterSource.GetNewRecordParam_Filter(null == DataSource ? CurrentListType : DataSource.TagName);
            string[] arr = { GlobalConstants.qPrefNEW_RECORD + Guid.NewGuid().ToString(), sListType };
            string s = string.Format("FilterEditor.aspx?ID={0}&TagName={1}", arr);
            AppEnvironment.PageNavigator.Redirect(AppEnvironment.PageNavigator.AddReturnUrlParam(s));


        }

        protected virtual void OnDelete()        
        {
            if (null == DataSource)
                return;
            string s = DataSource.TagName;
            AppEnvironment.FilterSource.Delete(DataSource);
            QueryStringTools.RefreshPageWitchNewParams(string.Format("ListTagName={0}", s));
        }
        protected virtual void OnEditFilter()
        {
            if (String.IsNullOrEmpty(CurrentId))
                return;
                        
            string s = string.Format("FilterEditor.aspx?ID={0}", CurrentId);
            AppEnvironment.PageNavigator.Redirect(AppEnvironment.PageNavigator.AddReturnUrlParam(s));


        }

        #endregion

        public  ScriptEngine GetListWhere()
        {
            if (null == DataSource )
                return null;

            return DataSource.Where;
        }


        //#region IFilterBody Members

        //public Func<ScriptEngine> FilterScriptEngine
        //{
        //    get { return GetListWhere; }
        //}


      
        //public Func<bool> OnShowHideConditionList 
        //{
        //    get{return _OnShowHideConditionList;} 
        //}        
        

        //#endregion



        #region Члены IFilterPanel

        private Filter GetDataSource()
        {
            return this.DataSource; 
        }
        Func<Filter> IFilterPanel.DataSource
        {
            get { return GetDataSource; }
        }

        #endregion
    }
}
